package objects2d;
import box2D.collision.shapes.B2PolygonShape;
import box2D.dynamics.B2BodyDef;
import box2D.dynamics.B2FixtureDef;
import box2D.dynamics.B2World;
import box2D.dynamics.B2Body;
import data.GlobalData;
import data.Object2DData;
import openfl.display.Bitmap;
import openfl.display.Sprite;

/**
 * ...
 * @author Marcos Martinez
 */
class Brick2D
{
	private var m_cCanvas:Sprite;
	private var m_cWorld:B2World;

	private var m_cShape:B2PolygonShape;
	private var m_cBodyDef:B2BodyDef;
	private	var m_cBody:B2Body;
	private var m_cFixtureDef:B2FixtureDef;
	
	public function new(cWorld:B2World)
	{
		m_cCanvas = new Sprite();
		m_cWorld = cWorld;	
		
		// Add bodies
		m_cFixtureDef = new B2FixtureDef();
		m_cShape = new B2PolygonShape();
		m_cBodyDef = new B2BodyDef();
		m_cBodyDef.type = B2Body.b2_dynamicBody;
		m_cFixtureDef.density = 1.0;
		m_cFixtureDef.friction = 0.5;
		m_cFixtureDef.restitution = 0.1;
		m_cFixtureDef.shape = m_cShape;
	
		
	}
	public function setProperties(nDensity:Float, nFriction:Float, nRestitution:Float)
	{
		m_cFixtureDef.density = nDensity;
		m_cFixtureDef.friction = nFriction;
		m_cFixtureDef.restitution = nRestitution;
		
	}
	
	public function createBox(bmImage:Bitmap, nPosX:Int, nPosY:Int):Void
	{	
		m_cCanvas.addChild(bmImage);
		m_cShape.setAsBox( bmImage.width / (2*GlobalData.PHYSIC_SCALE),bmImage.height / (2*GlobalData.PHYSIC_SCALE));
		m_cBodyDef.position.set((nPosX) / GlobalData.PHYSIC_SCALE, (nPosY) / GlobalData.PHYSIC_SCALE);
		m_cBody = m_cWorld.createBody(m_cBodyDef);
		var cData :Object2DData = new Object2DData();
		cData.m_nName = "brick";
		m_cBody.setUserData(cData);
		m_cBody.createFixture(m_cFixtureDef);			
		updateTexture();		
	}
	
	public function updateTexture():Void
	{
		m_cCanvas.x = m_cBody.getPosition().x * GlobalData.PHYSIC_SCALE - m_cCanvas.width/2 ;
		m_cCanvas.y = m_cBody.getPosition().y * GlobalData.PHYSIC_SCALE - m_cCanvas.height/2;
	}
	public function getCanvas():Sprite
	{
		return m_cCanvas;
	}
	
	
}